from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from bets.models import UserProfile, Game, GameField, Tournament, Team, Player, TournamentResult, UserBet
from twisted.persisted.aot import Instance

class FieldsInline(admin.StackedInline):
    model = GameField
    extra = 1

class ResultsInline(admin.StackedInline):
    model = TournamentResult
    extra = 1    
    
class PlayersInline(admin.StackedInline):
    model = Player
    extra = 1

class GameAdmin(admin.ModelAdmin):
    inlines = [FieldsInline]
    list_display = ('name',)
    list_filter = ['name']    
    
class TeamAdmin(admin.ModelAdmin):
    inlines = [PlayersInline]
    list_display = ('name',)
    list_filter = ['game', 'tournament']
    
    def save_formset(self, request, form, formset, change):
        instances = formset.save()
        tmp_team = None
        for instance in instances:
            if type(instance) == Player:
                tmp_team = instance.team
        if tmp_team == None:
            return
        players = Player.objects.all().filter(team = tmp_team)
        tmp_team.rating = 0
        for player in players:
            tmp_team.rating += player.rating
        tmp_team.rating /= len(players)
        tmp_team.save()
        
class TournamentAdmin(admin.ModelAdmin):
    inlines = [ResultsInline]
    list_display = ('name',)
    list_filter = ['game']
    
    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            if type(instance) == TournamentResult:
                results = UserBet.objects.all().filter(tournament=instance.tournament, bet=instance.bet, active=1)
                for r in results:
                    user = User.objects.get(username=r.user)
                    if instance.result == r.value:
                        user.get_profile().gold += r.gold * r.bet.winnings
                        user.get_profile().save()
                    r.active = 0
                    r.save()
            instance.save()
        formset.save_m2m()        

class BMSUserInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'

class UserAdmin(UserAdmin):
    inlines = (BMSUserInline, )
    
class UserBetAdmin(admin.ModelAdmin):
    list_display = ('bet',)
    list_filter = ('tournament', 'active', )

# ... and, since we're not using Django's builtin permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
admin.site.unregister(User)

admin.site.register(User, UserAdmin)
admin.site.register(Game, GameAdmin)
admin.site.register(Team, TeamAdmin)
admin.site.register(Tournament, TournamentAdmin)
admin.site.register(UserBet, UserBetAdmin)
